require 'rubygems'
require 'memcache'
require 'set'

class MemCache
    def storeDetail(key, flags, exptime, val)
        server, cache_key = request_setup key
        socket = server.socket

        command = "set #{cache_key} #{flags} 0 #{val.size}\r\n#{val}\r\n"

        begin
            @mutex.lock if @multithread
            socket.write command
            result = socket.gets
            raise MemCacheError, $1.strip if result =~ /^SERVER_ERROR (.*)/
        rescue SocketError, SystemCallError, IOError => err
            server.close
            raise MemCacheError, err.message
        ensure
            @mutex.unlock if @multithread
        end
    end      

    def fetchDetails( key )
        server, cache_key = request_setup(key)
        socket = server.socket
        socket.write "get #{cache_key}\r\n"
        keyline = socket.gets # "VALUE <key> <flags> <bytes>\r\n"

        if keyline.nil? then
            server.close
            raise MemCacheError, "lost connection to #{server.host}:#{server.port}"
        end

        return nil if keyline == "END\r\n"

        #        unless keyline =~ /(\d+)\r/ then
        #            server.close
        #            raise MemCacheError, "unexpected response #{keyline.inspect}"
        #        end
        name, key, flags, length = keyline.split(/\s+/, 4)
        value = socket.read length.to_i
        socket.read 2 # "\r\n"
        socket.gets   # "END\r\n"
        return key, flags, value
    end

    def slocs(svr=@servers)
        raise MemCacheError, "No active servers" unless active?
        ss = []

        @servers.each do |server|
            sock = server.socket
            raise MemCacheError, "No connection to server" if sock.nil?

            begin
                sock.write "stats items\r\n"
                while line = sock.gets do
                    break if line == "END\r\n"
                    if line =~ /^STAT ([\w\:]+) ([\w\.\:]+)/ then
                        name = $1
                        ss.push(name.split(/:/)[1]) unless ss.include?(name.split(/:/)[1])
                    end
                end
            end
        end
        ss
    end

    def keys(slac, svr=@servers)
        raise MemCacheError, "No active servers" unless active?
        ss = []

        @servers.each do |server|
            sock = server.socket
            raise MemCacheError, "No connection to server" if sock.nil?

            begin
                sock.write "stats cachedump #{slac} 0\r\n"
                while line = sock.gets do
                    break if line == "END\r\n"
                    if line =~ /^ITEM (\w+) .*/ then
                        key = $1
                        ss.push(key)
                    end
                end
            end
        end
        ss
    end
end